package controllers

import (
	"fmt"
	"time"
	"strconv"
	"net/http"
	"meman/models/events"
	"meman/libs/paginator"
	"meman/models/alert"
	"meman/models/auth"
	"meman/sys/basic"
	"meman/sys/rpclient"
	"meman/libs/utils"
	"github.com/labstack/echo"
	"github.com/chaosue/echo-sessions"
	"github.com/labstack/echo/engine/standard"
)

func MsgListShow(c echo.Context) error  {

	//session 使用
	session := sessions.Default(c)
	var username string
	//中间件已判断,所以这里不需要判断
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}


	alertInfo := new(alert.Alert)

	logger := basic.Logger{}

	//获取跳转页面alertInfo 信息
	if flashes := session.Flashes("alertInfo"); len(flashes) > 0 {
		alertInfo = flashes[0].(*alert.Alert)
	}
	session.Save()

	var perPageNums = 0
	per := c.QueryParam("perPageNums")
	if per != "" {
		num,err := strconv.Atoi(per)
		if err != nil {
			alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "perPageNums转换int失败!") }
		}else {
			perPageNums = num
		}
	}

	classKey := utils.TrimSpace(c.QueryParam("class_key"))
	className := utils.TrimSpace(c.QueryParam("class_name"))
	conds := make(map[string]interface{})
	if classKey != "" {
		conds["class_key"] = classKey
	}
	if className != "" {
		conds["class_name"] = className
	}

	db, count := events.Count(events.TABLE_MSG_CLASSES, conds)
	p := paginator.NewPaginator(c.Request().(*standard.Request).Request, perPageNums, count)

	msg := events.Message{}
	result, err := msg.GetMsgList(db, conds, p.Page(), p.PerPageNums)
	if err != nil {
		logger.WriteMsg("error", fmt.Sprintf("[%s][MsgListShow]search msg list fail!", username))
		alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "查询失败请检查")}
	}

	c.Render(http.StatusOK, "msgList.tmpl", basic.H{
		"name":username,
		"data": result,
		"query":conds,
		"paginator": p,
		"alert":alertInfo,
	})

	return nil

}

//添加消息跳转
func MsgListAdd(c echo.Context) error  {
	//session 使用
	session := sessions.Default(c)
	var username string
	//中间件已判断,所以这里不需要判断
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}

	c.Render(http.StatusOK, "msgListAdd.tmpl", basic.H{
		"name":username,
	})

	return nil
}
//处理添加
func MsgListAddPost(c echo.Context) error  {

	//session 使用
	session := sessions.Default(c)
	var username string
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}

	alertInfo := new(alert.Alert)

	logger := basic.Logger{}

	classKey := utils.TrimSpace(c.FormValue("classKey"))
	className := utils.TrimSpace(c.FormValue("className"))
	comment := utils.TrimSpace(c.FormValue("comment"))


	if classKey == "" && className == "" {
		alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "分类名称或分类key不能为空")}
	}else {
		message := events.Message{
			ClassKey:classKey,
			ClassName:className,
			Comment:comment,
			CreateTime:time.Now().Unix(),
		}
		err := message.Insert()
		if err != nil {
			alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, fmt.Sprintf("新增失败,键和名称必须唯一,失败原因: %s ", err ))}
			logger.WriteMsg("error", fmt.Sprintf("[%s][添加消息分类][classKey:%s, className:%s, comment:%s] error!\r\n", username, classKey, className, comment))
		}else {
			logger.WriteMsg("info", fmt.Sprintf("[%s][添加消息分类][classKey:%s, className:%s, comment:%s]\r\n", username, classKey, className, comment))
			alertInfo = &alert.Alert{Flag:true, Msg:append(alertInfo.Msg, "添加消息分类成功")}
		}
	}

	session.AddFlash(alertInfo, "alertInfo")
	session.Save()

	c.Redirect(http.StatusFound,"/Event/MsgList/show")

	return nil

}



//更新跳转
func MsgListUpdate(c echo.Context) error  {
	//session 使用
	session := sessions.Default(c)
	var username string
	//中间件已判断,所以这里不需要判断
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}


	alertInfo := new(alert.Alert)

	logger := basic.Logger{}

	id := c.QueryParam("id")
	classId,err := strconv.Atoi(id)
	if err != nil {
		alertInfo = &alert.Alert{Flag:true, Msg:append(alertInfo.Msg, "id转换int失败!")}
	}

	msg := events.Message{}
	result, err := msg.FindById(classId)
	if err != nil {
		logger.WriteMsg("info", fmt.Sprintf("[%s][MsgListUpdate]find msg error:id:%s \r\n", username, id))
		alertInfo = &alert.Alert{Flag:true, Msg:append(alertInfo.Msg, "id查找msg失败!")}
	}


	c.Render(http.StatusOK, "msgListUpdate.tmpl", basic.H{
		"name":username,
		"data":result,
		"alert":alertInfo,
	})

	return nil
}

func MsgListUpdatePost(c echo.Context) error {

	//session 使用
	session := sessions.Default(c)
	var username string
	//中间件已判断,所以这里不需要判断
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}

	alertInfo := new(alert.Alert)

	id := utils.TrimSpace(c.QueryParam("id"))
	classKey := utils.TrimSpace(c.FormValue("classKey"))
	className := utils.TrimSpace(c.FormValue("className"))
	comment := utils.TrimSpace(c.FormValue("comment"))

	if id == "" && classKey == "" && className == "" {
		alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "分类id,分类key或分类名称为空!")}
	}else {
		logger := basic.Logger{}

		conds := make(map[string]interface{})
		conds["class_key"] = classKey
		conds["class_name"] = className
		conds["comment"] = comment

		classId,err := strconv.Atoi(id)
		if err != nil {
			alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "id 转换int失败!")}
		}

		message := events.Message{}
		err = message.Update(classId, conds)
		if err != nil {
			alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, fmt.Sprintf("更新失败:%s", err) )}
			logger.WriteMsg("error", fmt.Sprintf("[%s][更新消息分类][classKey:%s, className:%s, comment:%s] error!\r\n", username, classKey, className, comment))
		}else {
			logger.WriteMsg("info", fmt.Sprintf("[%s][更新消息分类][classKey:%s, className:%s, comment:%s]\r\n", username, classKey, className, comment))
			alertInfo = &alert.Alert{Flag:true, Msg:append(alertInfo.Msg, "更新成功!")}
		}

		c, err := rpclient.New(basic.Config.ListenAddr)
		if err != nil {
			alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, fmt.Sprintf("rpc client connect error:%s", err)) }
			logger.WriteMsg("error", fmt.Sprintf("[%s][MsgListUpdatePost]rpc client connect error:%s",username, err))
		}else {
			defer c.Close()
			var re interface{}
			re, err = c.Call("ClearDataCache", map[string]interface{}{})
			if re != true {
				logger.WriteMsg("error", fmt.Sprintf("[%s][MsgListUpdatePost]ClearDataCache error:",username, err))
				alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, fmt.Sprintf("rpc client Not cleared:%s", err)) }
			}
		}

		session.AddFlash(alertInfo, "alertInfo")
		session.Save()

	}

	c.Redirect(http.StatusFound,"/Event/MsgList/show")

	return nil
}


//删除跳转
func MsgListDelete(c echo.Context) error  {

	//session 使用
	session := sessions.Default(c)
	var username string
	//中间件已判断,所以这里不需要判断
	if user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User); ok {
		username = user.Info.Username
	}

	alertInfo := new(alert.Alert)

	logger := basic.Logger{}

	id := c.QueryParam("id")
	classId,err := strconv.Atoi(id)
	if err != nil {
		alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "id 转换int失败!")}
	}

	message := events.Message{}
	err = message.DeleteById(classId)
	if err != nil {
		alertInfo = &alert.Alert{Flag:false, Msg:append(alertInfo.Msg, "msg 删除失败!")}
		logger.WriteMsg("info", fmt.Sprintf("[%s][删除消息分类][id:%s] error!\r\n", username, id))
	}

	session.AddFlash(alertInfo, "alertInfo")
	session.Save()

	c.Redirect(http.StatusFound,"/Event/MsgList/show")

	return nil
}

